#!/usr/bin/env python

import gtk
import gtk.glade
import os

from ConfClient import ConfClient

class SettingsManager:
	"""Class to display settings window"""
	def __init__(self):
		"""Initialization, loading widgets from glade file and running dialog"""

#		load glade file with all our widgets
		self.gladefile = "/home/maks/btx-applet/SettingsManager.glade"
		self.widgetsTree = gtk.glade.XML(self.gladefile)

#		dictionary describing handlers for signals from UI
		cb_dic = {
			"but_ok_clicked_cb": self.OK,
			"but_cancel_clicked_cb": self.Cancel,
			}

#		connecting signals with handlers
		self.widgetsTree.signal_autoconnect(cb_dic)
		self.window = self.widgetsTree.get_widget("dialog1")

#		connecting to configuration
		self.cclient = ConfClient()
	
		if self.cclient.state:
#			config exists
			self.user, self.passw, self.domain, self.sendto = self.cclient.load_conf()		

#			if fields are not empty, show them, previously deleted '"' symbol from start and end
			if (self.user is not None and self.passw is not None and self.domain is not None):
				self.widgetsTree.get_widget("txt_user").set_text(self.user.strip("\""))
				self.widgetsTree.get_widget("txt_passw").set_text(self.passw.strip("\""))
				self.widgetsTree.get_widget("txt_domain").set_text(self.domain.strip("\""))
				self.widgetsTree.get_widget("txt_sendto").set_text(self.sendto.strip("\""))
#				set "Save?" checkbox to checked state
				self.widgetsTree.get_widget("ch_save").set_active(True)
		else:
#			set "Save?" checkbox to unchecked state
			self.widgetsTree.get_widget("ch_save").set_active(False)
#		run dialog
		self.window.run()		
		self.__destroy()

	def OK(self,widget):
		"""Saves configuration if ordered"""
#		load configuration from widgets to class fields
		self.user = self.widgetsTree.get_widget("txt_user").get_text()
		self.passw = self.widgetsTree.get_widget("txt_passw").get_text()
		self.domain = self.widgetsTree.get_widget("txt_domain").get_text()
		self.sendto = self.widgetsTree.get_widget("txt_sendto").get_text()
		if self.widgetsTree.get_widget("ch_save").get_active():
#			user wants to save configuration
			self.cclient.save_conf(
				self.user,
				self.passw,
				self.domain,
				self.sendto
				)

#		close window
		self.__destroy()

	def Cancel(self,widget):
		"""Cancel all modifications"""
		self.__destroy()

	def __destroy(self):	
		"""Close window"""		
		self.window.destroy()
